interface CustomLogger {
  info: (message: string, ...args: any[]) => void;
  error: (message: string, ...args: any[]) => void;
  warn: (message: string, ...args: any[]) => void;
  debug: (message: string, ...args: any[]) => void;
}

const LOG_LEVELS = {
  DEBUG: 0,
  INFO: 1,
  WARN: 2,
  ERROR: 3,
} as const;

type LogLevel = keyof typeof LOG_LEVELS;

// 获取当前环境的日志级别
const getCurrentLogLevel = (): number => {
  if (typeof window === 'undefined') return LOG_LEVELS.ERROR; // 服务器端默认只显示错误
  if (process.env.NODE_ENV === 'development') return LOG_LEVELS.DEBUG; // 开发环境显示所有日志
  return LOG_LEVELS.INFO; // 生产环境只显示 INFO 及以上级别
};

const CURRENT_LOG_LEVEL = getCurrentLogLevel();

export function createLogger(component: string): CustomLogger {
  const getTime = () => new Date().toISOString();
  const prefix = `[${component}]`;

  const shouldLog = (level: LogLevel): boolean => {
    return LOG_LEVELS[level] >= CURRENT_LOG_LEVEL;
  };

  const formatMessage = (level: string, message: string) => {
    return `${getTime()} ${prefix} ${level}: ${message}`;
  };

  return {
    debug: (message: string, ...args: any[]) => {
      if (shouldLog('DEBUG')) {
        console.debug(formatMessage('DEBUG', message), ...args);
      }
    },
    info: (message: string, ...args: any[]) => {
      if (shouldLog('INFO')) {
        console.info(formatMessage('INFO', message), ...args);
      }
    },
    warn: (message: string, ...args: any[]) => {
      if (shouldLog('WARN')) {
        console.warn(formatMessage('WARN', message), ...args);
      }
    },
    error: (message: string, ...args: any[]) => {
      if (shouldLog('ERROR')) {
        console.error(formatMessage('ERROR', message), ...args);
      }
    },
  };
}
